package com.lfx.concurrent;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Data {

    private String fileName;

    private String content;

    private boolean change;


    public Data(String filename, String content){
        this.fileName=filename;
        this.content=content;
    }


    public synchronized void change(String newContent){
        content=newContent;
        this.change=true;
    }

    public synchronized void save(){
        if(change){
            try {
                doSave();
                change=false;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void doSave() throws IOException {
        System.out.println("线程名:"+Thread.currentThread().getName()+"执行保存-------保存内容:"+content);
        File file=new File(fileName);
        FileWriter fileWriter=new FileWriter(file);
        fileWriter.write(content);
        fileWriter.close();
    }
}
